package com.kis.ioc.core;

import com.kis.ioc.anno.Controller;
import com.kis.ioc.anno.Dao;
import com.kis.ioc.anno.Property;
import com.kis.ioc.anno.Service;
import com.kis.ioc.util.BeanUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by yks on 15-11-14.
 */
public class BeanDefinitionList {
    private static List<BeanDefinition> beanDefinitions = new ArrayList<BeanDefinition>();

    public static void addBeanDefinition(BeanDefinition beanDefinition) {
        beanDefinitions.add(beanDefinition);
    }

    public static void addBeanDefinition(String id, String className) {
        BeanDefinition beanDefinition = new BeanDefinition(id, className);
        beanDefinitions.add(beanDefinition);
    }
    public static void addBeanDefinitionAndSetProperty(Class<?> clazz){
        String fullName = clazz.getName();
        String id ="";
        if(clazz.isAnnotationPresent(Dao.class)){
            id = clazz.getAnnotation(Dao.class).value();
        }else if(clazz.isAnnotationPresent(Service.class)){
            id = clazz.getAnnotation(Service.class).value();
        }else if(clazz.isAnnotationPresent(Controller.class)){
            id = clazz.getAnnotation(Controller.class).value();
        }
        if(id==null ||  "".equals(id.trim())){
            id = fullName.substring(fullName.lastIndexOf(".")+1).substring(0,1).toLowerCase()+ fullName.substring(fullName.lastIndexOf(".")+1).substring(1);
        }
        BeanDefinition bd  = new BeanDefinition(id,fullName);
        Field [] fields = BeanUtils.findDeclaredFields(clazz);
        if(fields!=null && fields.length>0){
            for(Field f:fields){
                if(f.isAnnotationPresent(Property.class)){
                    PropertyDefinition pd = new PropertyDefinition(f.getName(),id);
                    bd.getPropertyDefinitions().add(pd);
                }
            }
        }
        Method [] methods = BeanUtils.findDeclaredMethods(clazz);
//        for(Method m : methods){
//            if(m.isAnnotationPresent(RequestMapping.class)){
//                String path = m.getAnnotation(RequestMapping.class).value();
//                if(RequestMapingMap.getBeanName(path)!=null){
//                    throw new AjunIocException("RequestMapping's url is only ,now it is not only");
//                }
//                RequestMapingMap.put(path, id);
//            }
//        }
        addBeanDefinition(bd);
    }
    //返回class信息类的List
    public static List<BeanDefinition> getBeanDefinitions(){
        return beanDefinitions;
    }
}
